package scales.xml.impl
import scales.xml.{ItemOrElem, XmlChildren,
XmlItem, Text, XmlTree, XmlVersion,
ScalesXml, defaultPathOptimisation,
Doc, loadXmlReader, convertFromScalaXml,
emptyChildren, AttributeQName,
Namespace, Xml10}
import ScalesXml.xmlCBF
import scales.utils.resources.Loaner
import scales.xml.parser.strategies.{PathOptimisationStrategy, OptimisationToken}
import scales.xml.parser.sax.SaxSupport
trait Whitespace {
import scales.utils.collection.Tree
def normalizeSpaceS(str: String) = str.replaceAll("\\s{2,}", " ").trim
val mergeAdjacentText
: ((Option[XmlItem], XmlChildren), ItemOrElem) => (Option[XmlItem], XmlChildren)
= (pair: (Option[XmlItem], XmlChildren), item: ItemOrElem) =>
if (item.isLeft && item.left.get.isInstanceOf[Text])
if (pair._1.isDefined) {
val text = Text(pair._1.get.value + item.left.get.value)
(Some(text), (pair._2.dropRight(1) :+ (text)) : XmlChildren)
} else (Some(item.left.get), (pair._2 :+ (item)) : XmlChildren)
else
(None, (pair._2 :+ (item)) : XmlChildren)
def joinTextNodes(tree: XmlTree) : XmlTree =
Tree(tree.section, joinTextNodes(tree.children))
def joinTextNodes(children : XmlChildren) : XmlChildren =
children.foldLeft((None: Option[XmlItem], emptyChildren ))(mergeAdjacentText)._2
}
import org.xml.sax.XMLReader
trait XmlUtils {
def convertFromScalaXml[Token <: OptimisationToken]( elem : scala.xml.Elem, parsers : Loaner[XMLReader] with SaxSupport = DefaultXMLReaderFactoryPool, optimisationStrategy : PathOptimisationStrategy[Token] = defaultPathOptimisation, encoding : String = "UTF-8" )(implicit xmlVer : XmlVersion) : Doc = {
var out = new java.io.StringWriter()
val p = parsers
scala.xml.XML.write(out, elem, encoding, true, null)
import ScalesXml.readerToSource
loadXmlReader[Token](new java.io.StringReader(out.toString), parsers = p, strategy = optimisationStrategy)
}
def isEmptyTree(tree: XmlTree): Boolean =
(tree.children.isEmpty && tree.section.attributes.isEmpty)
val xsiNil : AttributeQName = Namespace.xsi.prefixed("xsi", "nil")(Xml10, IsFromParser)
def isNil(tree: XmlTree): Boolean = {
import ScalesXml._
tree.section.attributes(xsiNil).
map{b => java.lang.Boolean.parseBoolean(b.value) || (b.value == "1")}.getOrElse(false)
}
}
trait XmlUtilsImplicits {
class ToScales( elem : scala.xml.Elem)(implicit xmlVer : XmlVersion) {
def asScales[Token <: OptimisationToken](parsers : Loaner[XMLReader] with SaxSupport = DefaultXMLReaderFactoryPool, optimisationStrategy : PathOptimisationStrategy[Token] = defaultPathOptimisation, encoding : String = "UTF-8" ) = convertFromScalaXml(elem, parsers, optimisationStrategy, encoding)
}
implicit def toScalesXml( elem : scala.xml.Elem)(implicit xmlVer : XmlVersion) = new ToScales(elem)
}